from django.shortcuts import render
from django.shortcuts import HttpResponse
import json,time
from db.mydb import MyDBConnection
from db.utils.logutils import LogUtils
from db.dao.jobs import Jobs
from db.utils.dfutils import load_json_to_object
def jobs_index(request):
    current = 1#如果用户不提供，默认看第一页
    pagesize = 10#如果用户不提供，默认每页5条
    if request.method == 'GET':  #大小写
        myDBConnection = MyDBConnection()
        current = request.GET.get("current")
        pagesize = request.GET.get("pagesize")
        print(f'1111 {request.GET.get("current")}')
        offset = (int(current) - 1) * int(pagesize) #计算每页的第一条编号
        jobss_json = myDBConnection.fetch_data_by_sql(f"select * from jobs limit {offset},{pagesize}")
        msg = f'现在查看的是第{current}页，每页大小{pagesize}'
        print(jobss_json)
        code = 200
        rep_json =  {"code":code,"msg":msg,"jobs":jobss_json}
    if bool(request.GET.get('json'))==True:
        return HttpResponse(json.dumps(rep_json), content_type="application/json")
    else:
        return render(request, "jobs/index.html", rep_json)

def jobs_add(request):
    # p_id = request.POST.get("p_id")
    # p_name = request.POST.get("p_name")
    data = request.body.decode("utf-8")
    print(type(data))
    myDBConnection =MyDBConnection()
    jobs_json_obj = json.loads(data)
    print(jobs_json_obj)
    jobs = load_json_to_object(jobs_json_obj,Jobs())
    print(type(jobs))
    myDBConnection.insert_entity(jobs)
    pname = jobs.j_name
    print(pname)

    # ------------日志记录开始 ，使用自定义日志记录器LogUtils.log----------
    # path_name = 'd:log'
    path_name = '/usr/ftp/logs/jobs/'
    current_time = time.localtime(time.time())

    current_time_str = time.strftime('%Y-%m-%d', current_time)  # 参数2为格式化字符串
    print(current_time_str)
    file_name = current_time_str + 'jobs.log'
    LogUtils.log(path_name, file_name, jobs.format_str())
    # LogUtils.log(path_name,file_name)

    msg = f"{pname}球员添加成功"
    code = 200
    rep_json = {"code":code,"msg":msg}
    return HttpResponse(json.dumps(rep_json), content_type="application/json")

def get_jobsById(request):
    mywhere = []
    j_id = request.GET.get("j_id")
    myDBConnection = MyDBConnection()  # 连接数据库


    # 获取教育经历记录列表
    jobs_json = myDBConnection.fetch_data_by_sql(
        f"select * from jobs where j_id ='{j_id}'  ")
    code = 200
    msg = f'现在查看的是受{j_id}成功'
    rep_json = {"code": code, "msg": msg, "jobs": jobs_json}
    if bool(request.GET.get('json')) == True:
        return HttpResponse(json.dumps(rep_json, ensure_ascii=False), content_type="application/json")
    else:
        return render(request, "player/index.html", rep_json)